package libs

import (
	"encoding/json"
	"net/http"
	"strconv"
)

//var templates = template.Must(template.ParseFiles("./tmpl/upload.html"))
//func display(w http.ResponseWriter, tmpl string, data interface{}) {
//	templates.ExecuteTemplate(w, tmpl+".html", data)
//}

func UploadHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	//case "GET":
	//	display(w, "upload", nil)
	case "POST":
		/**
		底层通过调用multipartReader.ReadForm来解析
		如果文件大小超过maxMemory,则使用临时文件来存储multipart/form中文件数据
		*/
		r.ParseMultipartForm(128)
		//fmt.Println("r.Form:         ",r.Form)
		//fmt.Println("r.PostForm:     ",r.PostForm)
		//fmt.Println("r.MultiPartForm:",r.MultipartForm)

		form := r.MultipartForm
		md5List := map[string]string{}
		//获取 multi-part/form body中的form value
		//for k, v := range form.Value {
		//	fmt.Println(k, " = ", v)
		//	//md5List[k] = v[0]
		//}

		//获取 multi-part/form中的文件数据
		for _, v := range form.File {
			for i := 0; i < len(v); i++ {
				//fmt.Println("file part ",i,"-->")
				//fmt.Println("fileName   :",v[i].Filename)
				//fmt.Println("part-header:",v[i].Header)
				name, err := SaveFile(v[i])
				if err != nil {
					Loger.Println(err.Error())
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				Loger.Println("Upload File :", name)
				md5List[strconv.Itoa(i)] = name
			}
		}

		jsonStr, err := json.Marshal(md5List)
		if err != nil {
			Loger.Println(err.Error())
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Access-Control-Allow-Origin", "*")
		//w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
		w.Header().Set("Cache-Control", "post-check=0, pre-check=0")
		w.Header().Add("Cache-Control", "no-store, no-cache, must-revalidate")
		w.Header().Set("Pragma", "no-cache")
		w.Header().Set("Transfer-Encoding", "chunked")
		w.Header().Set("Vary", "Accept-Encoding")
		w.Header().Set("Connection", "close")
		//w.Header().Set("Content-Type", "application/json")
		w.Header().Set("Content-Type", "text/html;charset=utf-8")

		w.Write([]byte(jsonStr))
	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}
